package server.mobiles;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;


import server.main.Data;
import server.utility.Id;
import server.utility.Point2d;


public class Mobile implements Serializable {
	protected Point2d position;
	protected String name;
	protected Id id;
	protected Id map;
	protected boolean player;
	protected int health;
	protected int maxHealth = 100;
	
	public Mobile(String name) {
		super();
		this.name = name;
		this.id = Id.nextId();
		player=false;
		this.health = maxHealth;
	}
	
	public void move(Point2d vect){
		position.plus(vect);
	}

	public boolean isPlayer() {
		return player;
	}

	public void setPosition(Point2d p) {
		position=p;
	}
	
	public void kill(Mobile from){
		Data.getMap(map).onKilled(this);
	}

	public void setMap(Id map2) {
		if(map!=null)
			Data.getMap(map).onExit(this);
		map=map2;
		Data.getMap(map).onEnter(this);
	}
	

	public Id getMap() {
		return map;
	}

	public Id getId() {
		return id;
	}
	
	public String getName() {
		return name;
	}
	
	public String toString(){
		return name+";"+position+";"+id+";"+health+";"+maxHealth+"\n";
	}

	public Point2d getPosition() {
		return position;
	}
	
	public int getHealth(){
		return health;
	}
	
	public int getMaxHealth(){
		return maxHealth;
	}

	public ArrayList<Mobile> getVisibleMobile() {
		return Data.getMap(map).getMobiles();
	}
	
	private void readObject(ObjectInputStream in) throws IOException,
	ClassNotFoundException {
		int ver=in.readInt();
		
		switch(ver){
		
			case 1:{
				position = (Point2d)in.readObject();
				name = in.readUTF();
				id = (Id)in.readObject();
				map = (Id)in.readObject();
				player = in.readBoolean();
				health = in.readInt();
				maxHealth = in.readInt();
				
			}
		}
	}
	
	private void writeObject(ObjectOutputStream out) throws IOException {
		out.writeInt(1); //version
		
		out.writeObject(position);
		out.writeUTF(name);
		out.writeObject(id);
		out.writeObject(map);
		out.writeBoolean(player);	
		out.writeInt(health);
		out.writeInt(maxHealth);
		
	}

	public void changeHealth(int i) {
		this.health += i;
		if(this.health<=0)
			kill(null);
	}

	public void update() {
		// TODO Auto-generated method stub
		
	}

}
